<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            @click="openDrawer('add')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>
      <!-- 卡片的内容区 -->
      <el-table :data="list" stripe style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者"> </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览"> </el-table-column>
        <el-table-column prop="createdAt" label="更新日期" width="180">
        </el-table-column>
        <el-table-column label="操作" width="120">
          <!-- 利用作用域插槽 -->
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-view" @click="openDrawer('view', row.id)"></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 15, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 抽屉 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      :before-close="handleClose"
      size="50%"
    >
      <!-- 添加，修改操作，抽屉的内容是表单 -->
      <el-form
        v-if="drawerType !== 'view'"
        label-width="80px"
        :model="form"
        :rules="rules"
        ref="form"
      >
        <!-- 一行，内容 -->
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 预览操作，内容不是表单，就是一个div -->
      <div v-else class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import {
  ArtcleListAPI,
  addArticleAPI,
  deleteAricleAPI,
  articleAPI,
  updateArticleAPI
} from '@/api/artcle'
export default {
  name: 'article-page',
  // 注册富文本编辑器
  components: { quillEditor },
  data () {
    return {
      list: [], // 存储面经列表的数据
      total: 0, // 共有多少条数据
      current: 1, // 当前页码
      pageSize: 10, // 每页显示多少条数据
      drawer: false, // 控制抽屉的显示和隐藏
      drawerType: '', // 打开抽屉后的操作类型
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '标题必填', trigger: 'blur' }],
        content: [{ required: true, message: '内容必填', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.initData() // 调用获取列表的方法
  },
  methods: {
    async initData () {
      const res = await ArtcleListAPI({
        current: this.current,
        pageSize: this.pageSize
      })
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 删除方法
    async del (id) {
      try {
        await deleteAricleAPI(id)
        this.$message.success('删除成功')
        this.initData() // 删除成功后重新获取列表数据
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.message)
        } else {
          this.$message.error('删除失败')
        }
      }
    },
    // 每页多少条发生变化后触发
    handleSizeChange (val) {
      console.log(val)
      this.pageSize = val // 修改每页几条数据
      this.current = 1 // 修改页码
      this.initData() // 重新获取数据
    },
    // 当前页码发生变化后触发
    handleCurrentChange (val) {
      console.log(val)
      this.current = val // 修改页码
      this.initData() // 重新获取数据
    },
    // 打开抽屉的方法
    async openDrawer (type, id) {
      this.drawerType = type // 将操作类型，存储到变量中
      // 添加不需要获取面经详情
      if (type !== 'add') {
        // 获取面经详情
        const res = await articleAPI(id)
        // console.log(res)
        this.form.content = res.data.content
        this.form.stem = res.data.stem
        this.form.id = res.data.id
      }
      this.drawer = true
    },
    // 关闭抽屉之前执行的方法
    handleClose () {
      this.$refs.form?.resetFields() // 重置表单
      // delete this.form.id // 删除id属性有问题
      // 彻底重置表单
      this.form = {
        stem: '',
        content: ''
      }
      this.drawer = false // 关闭抽屉
    },
    // 点击确定，提交表单【可能是添加也可能是修改，所以要判断】
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 验证通过，可以提交数据
          // 判断是添加还是修改
          let msg = ''
          if (this.drawerType === 'add') {
            msg = '添加'
          } else {
            msg = '修改'
          }
          try {
            if (this.drawerType === 'add') {
              await addArticleAPI(this.form)
            } else {
              await updateArticleAPI(this.form)
            }
            // console.log(this.form)
            this.handleClose() // 关闭抽屉（清空表单）
            this.initData() // 重新渲染页面
            this.$message.success(msg + '成功') // 提示成功
          } catch (err) {
            if (err.response) {
              this.$message.error(err.response.data.message)
            } else {
              this.$message.error(msg + '失败，请稍后再试')
            }
          }
        }
      })
    }
  },
  computed: {
    // 定义一个计算属性，根据接受的不同数据，返回不同的标题
    drawerTitle () {
      if (this.drawerType === 'add') {
        return '添加面经'
      } else if (this.drawerType === 'edit') {
        return '编辑面经'
      } else {
        return '面经预览'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
